package com.cpi.cornpp.futurepurchase.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.util.MessageResources;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.customer.services.CustomerServices;
import com.cpi.cornpp.customer.view.CustomerView;
import com.cpi.cornpp.customerpurchase.view.CustomerPurchaseView;
import com.cpi.cornpp.futurepurchase.exception.FuturePurchaseException;
import com.cpi.cornpp.futurepurchase.form.FuturePurchaseForm;
import com.cpi.cornpp.futurepurchase.helper.FuturePurchaseHelper;
import com.cpi.cornpp.futurepurchase.services.FuturePurchaseService;
import com.cpi.cornpp.futurepurchase.view.FuturePurchaseView;
import com.cpi.cornpp.period.service.PeriodService;
import com.cpi.cornpp.product.services.ProductService;
import com.cpi.cornpp.product.view.ProductView;
import com.cpi.cornpp.productpurchase.view.ProductPurchaseView;
import com.cpi.cornpp.user.exception.UserException;
import com.cs.common.utils.StringUtils;

/**
 * Clase que administra la alta y edicion de 
 * un FuturePurchase.
 * @author 
 *
 */
public class FuturePurchaseAddAction extends MappingDispatchAction{	
	/** Identifier default workflow*/
	private final static String DEFAULT = "default";//$NON-NLS-1$
	/** Identifier fail workflow*/
	private static final String FAIL = "fail";
	/** Indentifier for list workflow*/
	private static final String LIST = "list";
	/** Identifier in the Request for insert status*/
	private static final String INSERT_STATUS = "insertStatus";//$NON-NLS-1$	
	/** Identifier in the Request for update status*/
	private static final String UPDATE_STATUS = "updateStatus";//$NON-NLS-1$
	/** Identifier in the Request for error messages*/
	private static final String ERROR_MESSAGE = "ERROR_MESSAGE";
	/** Identifier in the Request for info messages*/
	private static final String MESSAGE = "MESSAGE";
	/** Identifier in the Request for error messages list*/
	private static final String ERROR_MESSAGE_LIST = "ERROR_MESSAGE_LIST";
	/** Custom exception */
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$	
	/** Id del FuturePurchase a modificar*/
	private static final String FP_ID = "fpId";
	/** Id del Customer */
	private static final String CUSTOMER_ID = "customerId";
	/** Mensaje de insert*/
	private static final String RECORD_SAVED = "message.futurepurchase.record.save";
	/** Mensaje de update*/
	private static final String RECORD_UPDATED = "message.futurepurchase.record.update";		
	/** Mensaje de error seleccion de resultados vacia*/
	private static final String SELECT_AN_ITEM = "error.message.futurepurchase.select.element.results";
	/** Mensaje de error seleccion de remover vacia*/
	private static final String SELECT_ITEM_TO_REMOVE = "Seleccione al menos un elemento a remover";
	/** Mensaje de error numero de contratos incorrecto*/
	private static final String WRONG_CONTRACT_NUMBER = "error.message.futurepurchase.wrong.contract.numbere";
	/** Mensaje de error fecha incorrecta*/
	private static final String WRONG_DATE = "error.message.futurepurchase.wrong.date";
	/** Mensaje de error fecha incorrecta*/
	private static final String QUANTITY_EXCEEDED = "error.message.futurepurchase.quantity.exceeded";
	/** Mensaje de error precio incorrecto*/
	private static final String WRONG_PRICE = "error.message.futurepurchase.wrong.price";
	/** Mensaje de error fecha incorrecta*/
	private static final String ADD_AMOUNT_TO_ALL_CUSTOMERS = "error.message.futurepurchase.enter.amount.for.all.customers";	
	/** Mensaje de error ingresar cantidades para los productos*/
	private static final String ADD_AMOUNT_TO_ALL_PRODUCTS = "error.message.futurepurchase.enter.amount.for.all.products";

	/**UPDATE*/
	/**
	 * Seteo inicial de los componentes visuales y llenado 
	 * de datos de la pantalla de actualizar FuturePurchase
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *  
	 */
	public ActionForward goUpdate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {	
		FuturePurchaseForm futurePurchaseForm = null;
		FuturePurchaseView fpView = null;
		FuturePurchaseService fpService = null;
		String fpId = null;		
		
		fpId = request.getParameter(FP_ID);
		if(fpId==null || (fpId!=null && !StringUtils.numericString(fpId)))
			return mapping.findForward(LIST);
		futurePurchaseForm = (FuturePurchaseForm)form;
		futurePurchaseForm.reset();
		futurePurchaseForm.setResultCustomerViews(new ArrayList(0)); 
		futurePurchaseForm.setForwardYearList(FuturePurchaseHelper.getForwardYearList());
		futurePurchaseForm.setUpdateForm(true);
		
		
		PeriodService periodService = null;
		periodService = new PeriodService();
		List arrLperiodService = periodService.getActivePeriods();
		futurePurchaseForm.setArrLperiodService(arrLperiodService);		
		
		
		fpService = new FuturePurchaseService();
		fpView = fpService.getFuturePurchaseViewById(Integer.parseInt(fpId));
		futurePurchaseForm.setFuturePurchaseView(fpView);
		
		return mapping.findForward(DEFAULT);
		
	}
	
	/** Actualizar un <code>FuturePurchase</code> junto con sus elementos 
	 * hijos <code>CustomerPurchase</code> y <code>ProductPurchase</>
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseService futurePurchaseService = null;
		FuturePurchaseForm futurePurchaseForm = null;
		boolean updateStatus = false;
		ArrayList errorList = null;
		String messageError = null;
		MessageResources messageResources = null;
		HttpSession httpSession = null;
				
		futurePurchaseForm =  (FuturePurchaseForm) form;
		futurePurchaseForm.setUpdateForm(true);
		
		try{
			errorList = validateCustomers(futurePurchaseForm,request);
			httpSession = request.getSession(false);
			messageResources = getResources(request);
			if(errorList.size()>0){
				httpSession.setAttribute(ERROR_MESSAGE_LIST, errorList);
				return mapping.findForward(FAIL);
			}
			futurePurchaseService = new FuturePurchaseService();
		
			if (futurePurchaseForm !=null) { 
				updateStatus = futurePurchaseService.updateFuturePurchase(futurePurchaseForm.getFuturePurchaseView());
				request.setAttribute(UPDATE_STATUS, new Boolean(updateStatus));
			}			
		}catch(FuturePurchaseException userException){
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), userException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
				form.reset(mapping, request);
				throw userException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);
				return mapping.findForward(FAIL);
			}
		}catch(Exception exception){
			UserException userException = null;
			exception.printStackTrace(System.out);
			userException = new UserException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_LOGIN);
			httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
			form.reset(mapping, request);
			throw userException;
		}
		request.getSession(false).setAttribute(MESSAGE, messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), RECORD_UPDATED));
		futurePurchaseForm.reset();
		return mapping.findForward(DEFAULT);

	}
	
	/**ALTAS*/
	/**
	 * Seteo inicial de los componentes visuales de la
	 * pantalla de agregar FuturePurchase
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward go(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {	
		FuturePurchaseForm futurePurchaseForm = null;
		FuturePurchaseView view = null;
		CustomerView customerView = null;
		int actualPeriod = 0;
		
		futurePurchaseForm = (FuturePurchaseForm)form;
		futurePurchaseForm.setUpdateForm(false);
		view = new FuturePurchaseView();
		customerView = new CustomerView();
		futurePurchaseForm.setFuturePurchaseView(view);
		PeriodService periodService = null;
		periodService = new PeriodService();
		List arrLperiodService = periodService.getActivePeriods();
		actualPeriod = periodService.actualPeriod();
		view.setAccountFuturePeriodId(actualPeriod);
		view.setApplicationFuturePeriodId(actualPeriod);
		futurePurchaseForm.setCustomerViewSearch(customerView);
		futurePurchaseForm.setForwardYearList(FuturePurchaseHelper.getForwardYearList());
		futurePurchaseForm.setArrLperiodService(arrLperiodService);
		futurePurchaseForm.setResultCustomerViews(new ArrayList(0));
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward searchCustomers(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		CustomerView customerView = null;		
		CustomerServices service = null;
		Collection customers = null;
		
		futurePurchaseForm =  (FuturePurchaseForm) form;
		customerView = futurePurchaseForm.getCustomerViewSearch();
		customerView.setCustomerId(customerView.getDescription());
		service = new CustomerServices();
		customers = service.getCustomersList(customerView);		
		futurePurchaseForm.setResultCustomerViews(customers);		
		return mapping.findForward(DEFAULT);
	}
	
	
	/** Insertar un <code>FuturePurchase</code> junto con sus elementos 
	 * hijos <code>CustomerPurchase</code> y <code>ProductPurchase</>
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseService futurePurchaseService = null;
		FuturePurchaseForm futurePurchaseForm =null;
		int insertStatus = 0;
		ArrayList errorsList = null;		
		MessageResources messageResources = null;
		String messageError = null;
		HttpSession httpSession = null;
		
		futurePurchaseForm =  (FuturePurchaseForm) form;
		errorsList = new ArrayList(0);
		errorsList = validateCustomers(futurePurchaseForm,request);
		
		if(errorsList.size()>0){
			request.getSession(false).setAttribute(ERROR_MESSAGE_LIST, errorsList);
			return mapping.findForward(FAIL);
		}		
		futurePurchaseService = new FuturePurchaseService();
		try{
			httpSession = request.getSession(false);
			messageResources = getResources(request);
			if (futurePurchaseForm !=null) { 
				insertStatus = futurePurchaseService.insertFuturePurchase(futurePurchaseForm.getFuturePurchaseView());
				request.setAttribute(INSERT_STATUS,new Boolean(insertStatus > 0));
			}			
		}catch(FuturePurchaseException userException){
			
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), userException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
				form.reset(mapping, request);
				throw userException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);
				return mapping.findForward(FAIL);
			}
		}catch(Exception exception){
			UserException userException = null;
			exception.printStackTrace(System.out);
			userException = new UserException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_LOGIN);
			httpSession.setAttribute(CUSTOM_EXCEPTION, userException);
			form.reset(mapping, request);
			throw userException;
		}
		request.getSession(false).setAttribute(MESSAGE, messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), RECORD_SAVED));
		futurePurchaseForm.reset();
		return mapping.findForward(DEFAULT);

	}
	
	/** Agregar un <code>CustomerPurchase</code> a la compra* 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward addCustomerToPurchase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		String[] selectedCustomerIds = null;
		HttpSession httpSession = null;
		Collection resultCustomers;
		List aux;
		Iterator it1 = null;
		MessageResources messageResources = null;
		
		httpSession = request.getSession();
		messageResources = getResources(request);				
		futurePurchaseForm =  (FuturePurchaseForm) form;		
		//Ids de los clientes seleccionados
		selectedCustomerIds = futurePurchaseForm.getSelectedCustomerIds();
		if(selectedCustomerIds!=null && !(selectedCustomerIds.length > 0)){
			request.getSession(false).setAttribute(ERROR_MESSAGE, messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), SELECT_AN_ITEM));
			return mapping.findForward(DEFAULT);
		}		
		//Ya tenemos en memoria los objetos clientes resultado de la busqueda, 
		//de ahi sacar los que se seleccionaron haciendo match con el customerId
		resultCustomers = futurePurchaseForm.getResultCustomerViews();		
		aux = Arrays.asList(selectedCustomerIds);
		
		//Asignar al futurePurchaseView los objetos clientes seleccionados
		it1 = resultCustomers.iterator();	
		while(it1.hasNext()){
			CustomerView c = (CustomerView)it1.next();
			if(aux.contains(c.getCustomerId())){				
				CustomerPurchaseView customerPurchaseView = new CustomerPurchaseView();
				customerPurchaseView.setCustomerId(c.getCustomerId());
				customerPurchaseView.setDescription(c.getDescription());
				if(futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().size()==0){											
					futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().add(customerPurchaseView);
				}else if(!futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().contains(customerPurchaseView)){
					futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().add(customerPurchaseView);
				}					
			}
		}		
		//request.setAttribute(CUSTOMERS_IN_PURCHASE, futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases());
		selectedCustomerIds = new String[]{};
		futurePurchaseForm.setSelectedCustomerIds(selectedCustomerIds);
		return mapping.findForward(DEFAULT);
	}
	
	/** Remover un <code>CustomerPurchase</code> de la compra* 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward removeCustomerFromPurchase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		String[] removedCustomerIds = null;		
		List aux;
		FuturePurchaseView view = null;
		
		futurePurchaseForm =  (FuturePurchaseForm) form;		
		//Ids de los clientes seleccionados
		removedCustomerIds = futurePurchaseForm.getRemovedCustomerIds();
		if(removedCustomerIds!=null && !(removedCustomerIds.length > 0)){
			request.getSession(false).setAttribute(ERROR_MESSAGE, SELECT_ITEM_TO_REMOVE);
			return mapping.findForward(DEFAULT);
		}
		view = futurePurchaseForm.getFuturePurchaseView();
		
		aux = Arrays.asList(removedCustomerIds);
		
		List customerPurchases = new ArrayList();
		
		//Asignar al futurePurchaseView los objetos clientes seleccionados
		
		List cps = view.getCustomerPurchases();
		Iterator it = cps.iterator();
		while(it.hasNext()){
			CustomerPurchaseView c = (CustomerPurchaseView)it.next();
			if(!aux.contains(c.getCustomerId())){
				c.setRemoved(false);
				customerPurchases.add(c);
			}else{
				c.setRemoved(true);			
			}
			
		}
		view.setCustomerPurchases(customerPurchases);
		
		//request.setAttribute(CUSTOMERS_IN_PURCHASE, futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases());
		removedCustomerIds = new String[]{};
		futurePurchaseForm.setSelectedCustomerIds(removedCustomerIds);
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * Abrir Ventana de asignacion de productos al cliente
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward openProductAssignment(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception {
		
		FuturePurchaseForm futurePurchaseForm = null;
		int index = 0;  
		String id = null;
		CustomerPurchaseView cpView = null;		
		id = request.getParameter(CUSTOMER_ID);
		futurePurchaseForm = (FuturePurchaseForm)form;
		cpView = new CustomerPurchaseView();
		futurePurchaseForm.setResultProducts(new ArrayList(0));
		cpView.setCustomerId(id);
		index = futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().indexOf(cpView);
		if( index >= 0 ){
			cpView = (CustomerPurchaseView)futurePurchaseForm.getFuturePurchaseView().getCustomerPurchases().get(index);
		}
		futurePurchaseForm.getFuturePurchaseView().setCustomerPurchaseSelected(cpView);	
		
		return mapping.findForward(DEFAULT);		
	}
	
	/**
	 * Busqueda de productos
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward searchProducts(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		ProductView productView = null;		
		ProductService service = null;
		List products = null;
		
		futurePurchaseForm =  (FuturePurchaseForm) form;
		productView = futurePurchaseForm.getProductViewSearch();
		service = new ProductService();
		products = service.getProductList(productView);	
		futurePurchaseForm.setResultProducts(products);
		//futurePurchaseForm.setResultCustomerViews(customers);
		//request.setAttribute(PRODUCTS_IN_RESULT, products);
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * Agregar un producto a un cliente
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward addProductToCustomerPurchase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		String[] selectedProductIds = null;
		HttpSession httpSession = null;
		List resultProducts;
		List aux;
		
		httpSession = request.getSession();
		futurePurchaseForm =  (FuturePurchaseForm) form;		
		//Ids de los clientes seleccionados
		selectedProductIds = futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getSelectedProductIds();
		if(selectedProductIds!=null && !(selectedProductIds.length > 0)){
			request.getSession(false).setAttribute(ERROR_MESSAGE, messages.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), SELECT_AN_ITEM));
			return mapping.findForward(DEFAULT);
		}
			
		//Ya tenemos en memoria los objetos clientes resultado de la busqueda, 
		//de ahi sacar los que se seleccionaron haciendo match con el customerId
		resultProducts = futurePurchaseForm.getResultProducts();		
		aux = Arrays.asList(selectedProductIds);
		
		//Asignar al futurePurchaseView los objetos clientes seleccionados		
		for (int i = 0; i < resultProducts.size(); i++) {
			ProductView p = (ProductView)resultProducts.get(i);
			if(aux.contains(p.getProductId())){				
				ProductPurchaseView ppView = new ProductPurchaseView();
				ppView.setProductId(p.getProductId());
				ppView.setDescription(p.getDescription());
				if(futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews().size()==0){											
					futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews().add(ppView);
				}else if(!futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews().contains(ppView)){
					futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews().add(ppView);
				}					
			}
		}		
		//request.setAttribute(PRODUCTS_IN_PURCHASE, futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews());
		futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().setSelectedProductIds(new String[0]); 
		return mapping.findForward(DEFAULT);
	}	
	
	/**
	 * Agregar un producto a un cliente
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward removeProductFromCustomerPurchase(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		FuturePurchaseForm futurePurchaseForm = null;
		String[] removedProductIds = null;		
		List aux;
		FuturePurchaseView view = null;		
		
		futurePurchaseForm =  (FuturePurchaseForm) form;		
		//Ids de los clientes seleccionados
		removedProductIds = futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getRemovedProductIds();
		if(removedProductIds!=null && !(removedProductIds.length > 0)){
			request.getSession(false).setAttribute(ERROR_MESSAGE, SELECT_ITEM_TO_REMOVE);
			return mapping.findForward(DEFAULT);
		}
		view = futurePurchaseForm.getFuturePurchaseView();

		aux = Arrays.asList(removedProductIds);
		
		
		//Esta lista auxiliar es para tratar el fail-fast iterator
		List productPurchasesViews = new ArrayList();
		List cps = view.getCustomerPurchaseSelected().getProductPurchaseViews();
		Iterator it = cps.iterator();
		while(it.hasNext()){
			ProductPurchaseView p = (ProductPurchaseView)it.next();		
			if(!aux.contains(p.getProductId())){
				productPurchasesViews.add(p);												
			}
		}		
		view.getCustomerPurchaseSelected().setProductPurchaseViews(productPurchasesViews);
		
		//request.setAttribute(PRODUCTS_IN_PURCHASE, futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().getProductPurchaseViews());
		futurePurchaseForm.getFuturePurchaseView().getCustomerPurchaseSelected().setRemovedProductIds(new String[0]);
		return mapping.findForward(DEFAULT);
	}	
	
	/**
	 * Regresar a la pantalla principal de alta
	 * despues de agregar los productos
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward saveAssignProducts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ArrayList errors = null;
		FuturePurchaseForm futurePurchaseForm = null;
		futurePurchaseForm = (FuturePurchaseForm)form;		
		errors = validateProducts(futurePurchaseForm, request);
		if(errors.size()>0){
			request.getSession(false).setAttribute(ERROR_MESSAGE_LIST, errors);
			return mapping.findForward(FAIL);
		}
		return mapping.findForward(DEFAULT);
	}

	public ActionForward cancelAssignProducts(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.findForward(DEFAULT);		
	}
	

	/**
	 * Validacion de campos.
	 * @param form
	 * @return
	 */
	public ArrayList validateCustomers(FuturePurchaseForm  form, HttpServletRequest request) {
		 ArrayList errors = new ArrayList(0);
		 ArrayList errorProducts = new ArrayList(0);
		 FuturePurchaseView view = form.getFuturePurchaseView();
		 MessageResources messageResources = null;
		 HttpSession httpSession = null;
		 List cps = null;
		 Iterator it1 = null;
		 
		 form.getFuturePurchaseView();
		 httpSession = request.getSession();
		 messageResources = getResources(request);
		 if(!(view.getQuantity()>0)){
			 errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY),WRONG_CONTRACT_NUMBER));
		 }
		 if(view.getPurchaseDate()==null || StringUtils.emptyString(view.getPurchaseDate().trim())){
			 errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY),WRONG_DATE));
		 }
		 if(!(view.getUnitPrice()>=0)){
			 errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY),WRONG_PRICE));
		 }	 
		 
		 if(form.getTotalEarly() < 0 )
			 errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY),QUANTITY_EXCEEDED));
		 
		 cps = view.getCustomerPurchases();
		 if(cps!=null && (cps.size()>0)){
				it1 = cps.iterator();
				while(it1.hasNext()){
					CustomerPurchaseView c = (CustomerPurchaseView)it1.next();
					if((c.getQuantityDirect()==0) && c.getQuantityFixed()==0){
						errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY),ADD_AMOUNT_TO_ALL_CUSTOMERS));
						break;
					}
			}
		 }
			
		 errorProducts = validateProducts(form, request);
		 if(errorProducts.size()>0)
			 errors.add(errorProducts);
		 
 
		 return errors;	 
	}
	
	/**
	 * Validacion de campos.
	 * @param form
	 * @return
	 */
	public ArrayList validateProducts(FuturePurchaseForm  form, HttpServletRequest request) {		
		 List cps = null;
		 Iterator it1 = null;
		 Iterator it2 = null;
		 ArrayList errors = new ArrayList(0);
		 FuturePurchaseView view = form.getFuturePurchaseView();
		 MessageResources messageResources = null;
		 HttpSession httpSession = null;

		 messageResources = getResources(request);
		
		 httpSession = request.getSession(); 
		 cps = view.getCustomerPurchases();
		 if(cps!=null && (cps.size()>0)){
			it1 = cps.iterator();
			while(it1.hasNext()){
				CustomerPurchaseView c = (CustomerPurchaseView)it1.next();					
				List pps = c.getProductPurchaseViews();
				if(pps!=null){					
					it2 = pps.iterator();
					while(it2.hasNext()){
						ProductPurchaseView p = (ProductPurchaseView)it2.next();						
						if(!(p.getQuantity()>0)){
							errors.add(messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), ADD_AMOUNT_TO_ALL_PRODUCTS));
							break;
						}					
					}
				}
				 			 
			 }			 
		 } 
		 return errors;	 
	}
}
